<template>
  <view class="cart-item">
    <!-- 选择框 -->
    <view class="item-select" @click="$emit('select', item.id)">
      <uni-icons 
        :type="selected ? 'checkbox-filled' : 'circle'" 
        size="24" 
        :color="selected ? '#ff5500' : '#999'"
      ></uni-icons>
    </view>

    <!-- 商品信息 -->
    <view class="item-content" @click="goToDetail">
      <!-- 商品图片 -->
      <image class="product-image" :src="item.productImg" mode="aspectFill"></image>
      
      <!-- 商品详情 -->
      <view class="product-info">
        <!-- 商品名称 -->
        <view class="product-name-wrap">
          <text class="product-name">{{ item.productName || item.name }}</text>
          <text class="product-tag" v-if="item.tags">{{ item.tags }}</text>
        </view>

        <!-- 商品规格 -->
        <view class="product-spec" v-if="specInfo">{{ specInfo }}</view>
        
        <!-- 价格和数量控制 -->
        <view class="price-quantity">
          <text class="price">¥{{ item.price.toFixed(2) }}</text>
          
          <view class="quantity-control">
            <button 
              class="quantity-btn minus" 
              :class="{ disabled: item.quantity <= 1 }"
              @click.stop="updateQuantity(-1)"
            >
              <uni-icons type="minus" size="20" color="#666"></uni-icons>
            </button>
            
            <input 
              type="number" 
              class="quantity-input"
              :value="item.quantity"
              @input="onQuantityInput"
              @blur="onQuantityBlur"
            />
            
            <button 
              class="quantity-btn plus"
              :class="{ disabled: item.quantity >= item.allocatedStock }"
              @click.stop="updateQuantity(1)"
            >
              <uni-icons type="plus" size="20" color="#666"></uni-icons>
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 删除按钮 -->
    <view class="delete-btn" @click="handleDelete">
      <uni-icons type="trash" size="20" color="#999"></uni-icons>
    </view>
  </view>
</template>

<script>
export default {
  name: 'CartItem',
  props: {
    item: {
      type: Object,
      required: true
    },
    selected: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    specInfo() {
      if (!this.item.specInfo) return ''
      try {
        const specs = JSON.parse(this.item.specInfo)
        return Object.entries(specs)
          .map(([key, value]) => `${key}: ${value}`)
          .join('、')
      } catch (e) {
        console.error('Failed to parse specInfo:', e)
        return this.item.specInfo
      }
    },
    maxQuantity() {
      // 如果有分配的库存，使用分配的库存作为最大值
      if (typeof this.item.allocatedStock === 'number' && this.item.allocatedStock > 0) {
        return this.item.allocatedStock
      }
      // 否则返回一个较大的数值
      return 99
    }
  },
  methods: {
    // 跳转到商品详情页
    goToDetail() {
      if (!this.item.productId) {
        uni.showToast({
          title: '商品信息有误',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/product/detail/index?id=${this.item.productId}`,
        fail: (err) => {
          console.error('跳转失败:', err)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    },

    // 更新商品数量
    updateQuantity(delta) {
      const newQuantity = this.item.quantity + delta
      
      if (newQuantity < 1) {
        uni.showToast({
          title: '数量不能小于1',
          icon: 'none'
        })
        return
      }
      
      if (newQuantity > this.maxQuantity) {
        uni.showToast({
          title: '已达到最大购买数量',
          icon: 'none'
        })
        return
      }
      
      this.$emit('update-quantity', this.item.id, newQuantity)
    },

    // 处理数量输入
    onQuantityInput(e) {
      const value = parseInt(e.detail.value)
      if (isNaN(value)) return
      
      if (value < 1) {
        uni.showToast({
          title: '数量不能小于1',
          icon: 'none'
        })
        return
      }
      
      if (value > this.maxQuantity) {
        uni.showToast({
          title: '已达到最大购买数量',
          icon: 'none'
        })
        return
      }
      
      this.$emit('update-quantity', this.item.id, value)
    },

    // 处理数量输入框失焦
    onQuantityBlur(e) {
      const value = parseInt(e.detail.value)
      if (isNaN(value) || value < 1) {
        this.$emit('update-quantity', this.item.id, 1)
      }
    },

    // 处理删除商品
    handleDelete() {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个商品吗？',
        success: (res) => {
          if (res.confirm) {
            this.$emit('delete', [this.item.id])
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.cart-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }

  .item-select {
    padding: 20rpx;
    margin-left: -20rpx;
  }

  .item-content {
    flex: 1;
    display: flex;
    margin: 0 20rpx;

    .product-image {
      width: 180rpx;
      height: 180rpx;
      border-radius: 12rpx;
      background-color: #f5f5f5;
    }

    .product-info {
      flex: 1;
      margin-left: 20rpx;
      display: flex;
      flex-direction: column;
      min-height: 180rpx;

      .product-name-wrap {
        .product-name {
          font-size: 28rpx;
          color: #333;
          line-height: 1.4;
          margin-bottom: 10rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }

        .product-tag {
          display: inline-block;
          font-size: 22rpx;
          color: #ff5500;
          background-color: #fff0e5;
          padding: 4rpx 12rpx;
          border-radius: 4rpx;
          margin-left: 12rpx;
          margin-top: 8rpx;
        }
      }

      .product-spec {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 10rpx;
      }

      .price-quantity {
        margin-top: auto;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .price {
          font-size: 32rpx;
          color: #ff5500;
          font-weight: bold;
        }

        .quantity-control {
          display: flex;
          align-items: center;
          border: 1rpx solid #eee;
          border-radius: 8rpx;
          overflow: hidden;

          .quantity-btn {
            width: 60rpx;
            height: 60rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f8f8f8;
            transition: all 0.2s;

            &.disabled {
              opacity: 0.5;
            }

            &:active {
              background-color: #f0f0f0;
            }
          }

          .quantity-input {
            width: 80rpx;
            height: 60rpx;
            text-align: center;
            font-size: 28rpx;
            color: #333;
            background-color: #fff;
            border-left: 1rpx solid #eee;
            border-right: 1rpx solid #eee;
          }
        }
      }
    }
  }

  .delete-btn {
    padding: 20rpx;
    margin-right: -20rpx;
  }
}
</style> 